package com.bourne.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

@Component
public class AESUtil {

    static Logger goodsLog = LoggerFactory.getLogger(AESUtil.class);

    private static final String CIPHERINSTANCE = "AES/ECB/PKCS5Padding";

    private static final String ENCRYPTIONTYPE = "AES";

    private static final String CODETYPE = "utf-8";

    /**
     * 加密
     * @param str
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String str, String sKey) throws Exception {
        if (StringUtils.isBlank(str) || StringUtils.isBlank(sKey)) {
            return null;
        }
        if (sKey.length() != 16) {
            return null;
        }
        byte[] raw = sKey.getBytes(CODETYPE);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ENCRYPTIONTYPE);
        Cipher cipher = Cipher.getInstance(CIPHERINSTANCE);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(str.getBytes(CODETYPE));
        return new Base64().encodeToString(encrypted);
    }

    /**
     * 解密
     * @param str
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String str, String sKey) {
        try {
            if (StringUtils.isBlank(str) || StringUtils.isBlank(sKey)) {
                return null;
            }
            if (sKey.length() != 16) {
                return null;
            }
            byte[] raw = sKey.getBytes(CODETYPE);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ENCRYPTIONTYPE);
            Cipher cipher = Cipher.getInstance(CIPHERINSTANCE);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(str);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, CODETYPE);
                return originalString;
            } catch (Exception e) {
                goodsLog.error(e.getMessage() + "===》AES解密异常");
                return null;
            }
        } catch (Exception ex) {
            goodsLog.error(ex.getMessage() + "===》AES解密异常");
            return null;
        }
    }
}
